import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:get/get.dart';

import '../../../common/models/portal.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/index.dart';
import '../../../common/widgets/index.dart';
import 'index.dart';
import 'portal_webview.dart';

class PortalPage extends GetView<PortalController> {
  @override
  final String? tag;

  const PortalPage({Key? key, required this.tag}) : super(key: key);

  static void open(String portalId,
      {String title = '', String? pageId, String? portalParameters}) async {
    OLogger.d('open portal $portalId');
    final tag =
        '$portalId-${pageId != null && pageId.isNotEmpty ? pageId : 'noPageId'}';
    OLogger.d('open portal ====>  $tag ');
    Get.lazyPut<PortalController>(() => PortalController(), tag: tag);
    OLogger.d('open portal to .......');
    // await Get.to(() => PortalPage(tag: tag),
    //     arguments: {"portalId": portalId, "title": title, "pageId": pageId, "portalParameters": portalParameters},
    //     preventDuplicates: false, preventDuplicateHandlingMode: PreventDuplicateHandlingMode.recreate);
    final args = PortalPageArgments(
        portalId: portalId,
        title: title,
        pageId: pageId,
        portalParameters: portalParameters);
    await pushPage(tag, args);
    OLogger.d('open portal ====>     ');
  }

  static Future<void> pushPage(String tag, PortalPageArgments args) async {
    final context = Get.context;
    if (context == null) {
      OLogger.d('pushPage context is null');
      return;
    }
    await Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) =>  PortalWebviewPage(tag: tag,),
          settings: RouteSettings(name: tag, arguments: args)),
    );
  }

  @override
  Widget build(BuildContext context) {
    PortalPageArgments? map;
    if (ModalRoute.of(context)?.settings.arguments is PortalPageArgments) {
      map = ModalRoute.of(context)?.settings.arguments as PortalPageArgments;
    }
    OLogger.d('message  build map = ${map?.toJson()}');
    return GetBuilder<PortalController>(
      tag: tag,
      builder: (_) {
        if (map != null) {
          controller.initFromNavigatorArgs(map.toJson());
        }
        return Obx(() {
          AppBar? appBar;
          if (controller.state.isPage) {
            appBar = AppBar(
                automaticallyImplyLeading: false,
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.arrow_back),
                      onPressed: () => controller.tapBackBtn(),
                    ),
                    IconButton(
                      icon: const Icon(Icons.close),
                      onPressed: () => controller.tapCloseBtn(),
                    ),
                    Expanded(flex: 1, child: Text(controller.state.title))
                  ],
                ),
                actions: [
                  O2UI.webviewPopupMenu(
                      (index) => controller.webviewMenuTap(index))
                ]);
          } else if (!controller.state.hiddenAppBar) {
            appBar = AppBar(
              title: Text(controller.state.title),
            );
          }
          return PopScope(
            canPop: false,
            onPopInvokedWithResult: (didPop, result) {
              OLogger.d('============>onPopInvokedWithResult $didPop');
              if (didPop) {
                return;
              }
              controller.tapBackBtn();
            },
            child: Scaffold(
              appBar: appBar,
              body: SafeArea(
                  child: controller.state.url.isEmpty
                      ? const Center(child: CircularProgressIndicator())
                      : _buildView()),
            ),
          );
        });
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return InAppWebView(
        key: controller.webViewKey,
        initialUrlRequest: URLRequest(url: WebUri(controller.state.url)),
        pullToRefreshController: controller.pullToRefreshController,
        initialSettings: InAppWebViewSettings(
          useShouldOverrideUrlLoading: true,
          useOnDownloadStart: true,
          javaScriptCanOpenWindowsAutomatically: true,
          mediaPlaybackRequiresUserGesture: false,
          applicationNameForUserAgent: O2.webviewUserAgent,
        ),
        onWebViewCreated: (c) {
          controller.setupWebviewJsHandler(c);
        },
        onLoadStop: (c, url) async {
          controller.pullToRefreshController.endRefreshing();
          OLogger.d("=====> onLoadStop url: $url");
        },
        onScrollChanged: (c, x, y) {
          OLogger.d("=====> onScrollChanged x: $x y: $y");
        },
        onReceivedError: (controller, request, error) {
          OLogger.d(
              "=====> onReceivedError url: ${request.url.toString()} message: ${error.toString()}");
        },
        onOverScrolled: (controller, x, y, clampedX, clampedY) {
          OLogger.d(
              "=====> onOverScrolled x: $x y: $y clampedX: $clampedX clampedY: $clampedY");
        },
        // onCreateWindow: (c, createWindowRequest) async {
        //   OLogger.d("创建新窗口，，，，${createWindowRequest.request.url}");
        // },
        shouldOverrideUrlLoading: (c, navigationAction) async {
          var uri = navigationAction.request.url!;
          OLogger.d("shouldOverrideUrlLoading uri: $uri");
          // c.loadUrl(urlRequest: URLRequest(url: uri));
          return NavigationActionPolicy.ALLOW;
        },
        onProgressChanged: (c, p) {
          controller.progressChanged(c, p);
          if (p == 100) {
            controller.pullToRefreshController.endRefreshing();
          }
        },
        // h5下载文件
        onDownloadStartRequest: (c, request) async {
          controller.webviewHelper.onFileDownloadStart(request);
        },
        onTitleChanged: ((c, title) {
          OLogger.d('修改网页标题： $title');
          final host = O2ApiManager.instance.getWebHost();
          if (title != null &&
              title.isNotEmpty &&
              controller.state.isPage &&
              !title.contains(host)) {
            controller.state.title = title;
          }
        }),
        onConsoleMessage: (c, consoleMessage) {
          OLogger.i("console: $consoleMessage");
        });
  }
}
